//
//  ORCodeViewController.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/3/23.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit
import AVFoundation

class ORCodeViewController: UIViewController ,UITabBarDelegate{

    /// 容器视图的高度约束
    @IBOutlet weak var containerHeightCons: NSLayoutConstraint!
    /// 冲击波的高度约束
    @IBOutlet weak var scanLineCons: NSLayoutConstraint!
    /// 冲击波
    @IBOutlet weak var scanLineView: UIImageView!
    /// TabBar
    @IBOutlet weak var customTabBar: UITabBar!
    
    
    /// 关闭按钮的点击事件
    @IBAction func closeClick(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    ///相册按钮的点击事件
    @IBAction func albumClick(_ sender: Any) {
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.设置TabBar的默认选中状态
        customTabBar.selectedItem = customTabBar.items![0]
        customTabBar.delegate = self
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //开始二维码扫描动画
        startAnimation()
        //开是扫描二维码
        startScan()
    }
    //MARK:-- 扫描二维码
    /// 扫描二维码
    func startScan() -> Void {
        //1.判断是否能够讲输入添加到会话中
        if !session.canAddInput(deviceinput) {
            return
        }
        //2.判断能够将输出设备添加到会话中
        if !session.canAddOutput(deviceOutput) {
            return
        }
        //3.将输入和输出设备都添加到会话中
        session.addInput(deviceinput)
        session.addOutput(deviceOutput)
        //4.设置输出设备能够解析的数据类型
        //注意:设置解析的数据类型,一定要在输出设备添加到会话中
        //设置输出设备的解析数据类型 为输出设备支持的类型
        deviceOutput.metadataObjectTypes = deviceOutput.availableMetadataObjectTypes
        //5.设置输出对象的代理,只要解析成功就会通知代理
        deviceOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        //6.添加预览图层
        view.layer.insertSublayer(previewLayer, at: 0)
        //添加回执图层到预览图层上面
        //previewLayer.addSublayer(drawLayer)
        //7.告诉session(会话)开始扫描
        session.startRunning()
    }
    /// 开始动画的方法
    //通过改变约束的方法来实现动画(必须要强制布局 layoutIfNeeded())
    private func startAnimation() -> Void {
        //1.让约束从顶部开始 
        //约束常量是可以修改的  修改约束常量比添加一个新的约束和移除一个约束要好
        scanLineCons.constant = -self.containerHeightCons.constant//等于view的高度的(负数)
        //修改约束之后一定要强制布局 对view中的子控件强制布局
        self.view.layoutIfNeeded()
        
        UIView.animate(withDuration: 2.0, animations: {
            //再次修改约束
            self.scanLineCons.constant = self.containerHeightCons.constant
            //设置动画循环次数
            UIView.setAnimationRepeatCount(MAXFLOAT)
            //再次强制布局
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
    
    //MARK: -- UITabBarDelegate  实现tabBar的代理
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        //1. 修改容器的高度
        if item.tag == 1 {
            print("二维码...")
            containerHeightCons.constant = 300;
        }else{
            print("条形码...")
            containerHeightCons.constant = 150;
        }
        //2.是停止动画 再次重新开始动画
        self.scanLineView.layer.removeAllAnimations()
        //3.再次重新开始动画
        startAnimation();
    }
    
    //MARK: 懒加载   扫描二维码的对象
    
    /// 创建会话
//    private lazy var session = { () -> AVCaptureSession in
//        let ta = AVCaptureSession()
//        return ta
//    }
    private lazy var session: AVCaptureSession = AVCaptureSession()//以上两种方式都是懒加载方式
    
    //创建输入设备
    private lazy var deviceinput: AVCaptureDeviceInput? = {
        //设置捕捉设备
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        //得到输入设备
        do{
            let Input = try AVCaptureDeviceInput.init(device: device)
            return Input
        }catch{
            print(error)
            return nil
        }
    }()
    
    //创建输出设备
    private lazy var deviceOutput: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    //创建预览图层
    private lazy var previewLayer = { ()-> AVCaptureVideoPreviewLayer in
        let layer = AVCaptureVideoPreviewLayer(session: self.session)!
        layer.frame = UIScreen.main.bounds
        return layer
    }()
    
    //创建用于绘制边缘的图层
    private lazy var drawLayer: CALayer = {
        let layer = CALayer()
        layer.frame = UIScreen.main.bounds
        return layer
    }()
}
extension ORCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
    
    //只要输设备解析数据就会调用这个方法
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        //输出对象输出的都是这个对象 AVMetadataMachineReadableCodeObject
        //1.转换坐标系
        for object in metadataObjects {
            //1.1先判断获取的数据是不是机器可识别的数据
            if object is AVMetadataMachineReadableCodeObject {
                //把二维码得到数据转换成我们能看到栋的数据
                let codeObject = object as! AVMetadataMachineReadableCodeObject//AVCaptureVideoPreviewLayer().transformedMetadataObject(for: object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject//object as! AVMetadataMachineReadableCodeObject
                //拿到二维码中数据信息
                //let dataString = codeObject.stringValue
                
                
                //拿到二维码获取的当前位子 CGPointCreateDictionaryRepresentation
                
                print("zhuanma zhihou ===",codeObject.corners)
            }
        }
        //print("saomiaoshuju=======",metadataObjects.last ?? 888)
    }
}


